<?php


namespace app\cms\community\thirdPartyApi\weChat;


use app\cms\community\thirdPartyApi\weChat\lib\payParams;
use iflow\exception\Adapter\HttpException;
use WeChat\Oauth;
use WeMini\Crypt;

/**
 * Class User
 * @mixin Oauth
 * @mixin Crypt
 * @package app\cms\community\thirdPartyApi\weChat
 */
class User
{
    // 公众号、小程序 基本配置
    public array $config;
    private Oauth $oauth;
    private Crypt $crypt;

    public function __construct(protected payParams $publicParams)
    {
        $this->config = $publicParams -> getConfig();
        $this->oauth = new Oauth($this->config);
        $this->crypt = new Crypt($this->config);
    }

    /**
     * 获取微信公众号用户信息
     * @param string $code
     * @return array
     */
    public function getWechatCommunityUserInfo(string $code): array
    {
        try {
            $user = $this->oauth->getOauthAccessToken($code);
            if (isset($user['openid'])) return $user;
        } catch (\Exception $exception) {
            throw new HttpException(502, $exception -> getMessage());
        }
        return [];
    }

    public function getOauthRedirect($state = '', string $scope = 'snsapi_base', string $redirect = ''): string {
        return $this->oauth -> getOauthRedirect($this->config['redirect_url'] . $redirect, $state, $scope);
    }

    public function __call(string $name, array $arguments) {
        // TODO: Implement __call() method.
        if (method_exists($this->oauth, $name)) return call_user_func([$this->oauth, $name], ...$arguments);
        return call_user_func([$this->crypt, $name], ...$arguments);
    }

}